<?php

declare(strict_types=1);

namespace App\Model;

use App\Model\Stat\StatDailyHostInfo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户资料表
 */
class UserProfile extends Model
{
    protected $connection = 'mysql';

    const HOST_CATE_NULL = 0;
    const HOST_CATE_A = 1;
    const HOST_CATE_B = 2;
    const HOST_CATE_C = 3;
    // const HOST_CATE_D = 4;
    const HOST_CATE = [
        UserProfile::HOST_CATE_A => '优质',
        UserProfile::HOST_CATE_B => '潜力',
        UserProfile::HOST_CATE_C => '普通',
        UserProfile::HOST_CATE_NULL => '未分级',
        // UserProfile::HOST_CATE_D => '未达标',
    ];

    const HOST_MARK_NORMAL = 1; //普通
    const HOST_MARK_OFFICIAL = 2; //内部扶持
    const HOST_MARK = [
        UserProfile::HOST_MARK_NORMAL => '正常',
        UserProfile::HOST_MARK_OFFICIAL => '内部扶持',
    ];

    //分成
    const HOST_SHARE = [
        '0.30' => '0.30',
        '0.35' => '0.35',
        '0.40' => '0.40',
        '0.45' => '0.45',
        '0.50' => '0.50',
//        '0.55' => '0.55'
    ];

    /**
     * 用户资料表
     */
    protected $table = 'user_profile';

    protected $fillable = [
        'user_id', 'is_official', 'nick_name', 'user_profile_id', 'city', 'gender', 'birthday', 'role', 'role_level', 'avatar', 'is_recommend', 'charm_value', 'rich_value', 'video_coin_setting', 'coin_setting', 'poster', 'host_time', 'video', 'self_intro', 'host_cate', 'voice', 'host_share', 'host_cate', 'invite_code', 'chat_coin_setting'
    ];

    //身份 - 普通用户
    const ROLE_USER = 1;
    //身份 - 声优
    const ROLE_HOST = 2;

    //技能配置
    const SKILL = [1 => '游戏达人', '恋爱达人', '唱歌达人', '哄睡达人', '叫醒达人'];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function usersRatingItem()
    {
        return $this->belongsTo(UsersRating::class, 'user_id', 'user_id');
    }

    public function rating()
    {
        return $this->belongsTo(UsersRating::class, 'user_id', 'id');
    }


    public function inviteUser()
    {
        return $this->belongsTo(UserProfile::class, 'invite_code', 'user_profile_id');
    }

    public function hostInfo()
    {
        return $this->belongsTo(HostInfo::class, 'user_id', 'user_id');
    }

    public function dailyHostInfo()
    {
        return $this->hasMany(StatDailyHostInfo::class, 'user_id', 'user_id');
    }


    public function userScore()
    {
        return $this->hasOne(UserScore::class,'user_id','user_id');
    }

    /**
     * 更新
     */
    static function updateInfo($userId = 0, $info = [])
    {
        return self::where('user_id', $userId)->limit(1)->update($info);
    }

    /**
     * 批量获取用户资料
     */
    static function getProfile($userId = 0)
    {
        if (!$userId) return null;
        $profile = self::where('user_id', $userId)->first();
        if (!$profile) return null;
        return $profile;
    }

    /**
     * 批量获取用户资料
     */
    static function getProfileById($userId = 0)
    {
        if (!$userId) return null;
        $profile = self::where('id', $userId)->first();
        if (!$profile) return null;
        return $profile;
    }

    /**
     * 批量获取用户资料
     */
    static function getInfoByProfileId($userProfileId = 0)
    {
        if (!$userProfileId) return null;
        $profile = self::where('user_profile_id', $userProfileId)->first();
        if (!$profile) return null;
        return $profile;
    }

    /**
     * 批量获取用户ID
     */
    static function getUidByProfileId($profileUserIds = [])
    {
        if (!$profileUserIds) return null;
        if (!is_array($profileUserIds)) $profileUserIds = [$profileUserIds];
        return self::whereIn('user_profile_id', $profileUserIds)->pluck('user_id')->toArray();
    }

    /**
     * 批量获取用户ID
     */
    static function getUidByProfileIdV2($profileUserIds = [])
    {
        if (!$profileUserIds) return null;
        if (!is_array($profileUserIds)) $profileUserIds = [$profileUserIds];
        return self::whereIn('user_profile_id', $profileUserIds)->pluck('user_id', 'user_profile_id')->toArray();
    }

    static function pickRandUserId()
    {
        $uids = self::where('role', self::ROLE_USER)->orderBy(DB::raw('rand()'))->first();
        return $uids->user_id;
    }

    /**
     * 邀请注册列表
     */
    static function inviteList($invitedUserId = 0)
    {
        $where = [
            ['invite_code', '<>', ''],
        ];
        $data = self::where($where)->select(['user_id', 'invite_code'])->get()->toArray();
        $list = [];
        array_walk($data, function ($item) use (&$list) {
            if (!isset($list[$item['invite_code']])) $list[$item['invite_code']] = [$item['user_id']];
            else {
                $list[$item['invite_code']][] = $item['user_id'];
            }
        });
        return $list;
    }

    /**
     * 设置默认头像
     */
    static function setDefaultAvatar($userId = 0, $profile = null)
    {
        if (!$profile) $profile = self::where('user_id', $userId)->first();
        if (!$profile) return false;
        $avatar = $profile->gender == 0 ? 'default/fe_avatar.jpeg' : 'default/ma_avatar.jpeg';
        // $posters = !$profile->poster ? [] : explode(',', trim($profile->poster, ','));
        // if ($posters) $posters[0] = $avatar;
        // $poster = implode(',', $posters);
        return $profile->update([
            'avatar' => $avatar,
            // 'poster' => $poster
        ]);
    }

    /**
     * 设置上一张头像
     */
    static function setLastAvatar($userId = 0)
    {
        $item = UserActLog::getLatestAvatar($userId);
        if (!$item) return self::setDefaultAvatar($userId);
        return self::where('user_id', $userId)->limit(1)->update(['avatar' => $item['detail']]);
    }

    static function getHostIds()
    {
        $where = [
            // 'gender' => 0,
            'role' => self::ROLE_HOST,
            // 'is_official' => 0
        ];
        return self::where($where)->pluck('user_id')->toArray();
    }

    public static function updateWagesByUserIds(array $ids, array $data)
    {
        return  self::whereIn('id', $ids)->update($data);
    }
}
